﻿using Common;
using Common.ResultFormat;
using Common.Swagger;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SystemService;

namespace Gateway.AuthorizationFilter
{
    //自定义中间件
    public class TestMiddelware
    {
        public RequestDelegate _next;
        private static SystemUrlService systemUrlService;
        public TestMiddelware(RequestDelegate next)
        {
            this._next = next;
        }
        public Task Invoke(HttpContext context)
        {
            return Task.Run(()=>
            {
                string url = context.Request.Path.Value;
                if (url == "/" || url.EndsWith("swagger.json") || url.Contains(".well-known/openid-configuration") || url.Contains("/api/Login/LoginIn") || url.Contains("swagger/index.html") || url.Contains("/favicon.ico") || url.Contains("/swagger/"))
                {
                    this._next(context);
                }
                else
                {
                    SystemUrlService systemUrlService = context.RequestServices.GetService(typeof(SystemUrlService)) as SystemUrlService;
                    var entity = SwaggerReadSummary.ReadSummary(context);
                    if (entity != null)
                    {
                        systemUrlService.CheckAndAdd(new SystemEntity.SystemUrlEntity() { Url = url, Name = entity.Name, ApplicationName = entity.ApplicationName, ControllerName = entity.ControllerName });
                    }
                    Console.WriteLine(context.TraceIdentifier + url);
                    string authorization = string.Empty;
                    if (context.Request.Headers.ContainsKey("authorization"))
                    {
                        authorization = context.Request.Headers["authorization"].ToString();
                    }
                    else if (context.Request.Query.ContainsKey("token"))
                    {
                        authorization = context.Request.Query["token"];
                    }
                    else if (context.Request.Query.ContainsKey("authorization"))
                    {
                        authorization = context.Request.Query["authorization"];
                    }
                    if (string.IsNullOrEmpty(authorization))
                    {
                        context.Response.ContentType = "text/html;charset=utf-8";
                        context.Response.WriteAsync(JsonConvert.SerializeObject(Result.Error("没权限")));
                    }
                    else
                    {
                        this._next(context);
                    }
                }
            });
        }
    }
}
